﻿using System.Diagnostics;
using Microsoft.VisualBasic;

namespace System
{
  [DebuggerStepThrough]
  public static class StringExtensions
  {
    public static string FormatString(this string str, params object[] args)
    {
      return String.Format(str, args);
    }
    public static bool IsEmpty(this string str)
    {
      return string.IsNullOrEmpty(str);
    }
    public static bool IsNotEmpty(this string str)
    {
      return !string.IsNullOrEmpty(str);
    }
    public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)
    {
      if (string.IsNullOrEmpty(startText) || string.IsNullOrEmpty(endText))
      {
        throw new ArgumentException("Start Text and End Text cannot be empty.");
      }
      string temp = s;
      if (ignoreCase)
      {
        temp = s.ToUpperInvariant();
        startText = startText.ToUpperInvariant();
        endText = endText.ToUpperInvariant();
      }
      int start = temp.IndexOf(startText);
      int end = temp.IndexOf(endText, start);
      return s.Substring(start, (end - start));
    }
    public static bool MatchesWildcard(this string text, string pattern)
    {
      int it = 0;
      while (text.CharAt(it) != 0 &&
             pattern.CharAt(it) != '*')
      {
        if (pattern.CharAt(it) != text.CharAt(it) && pattern.CharAt(it) != '?')
          return false;
        it++;
      }

      int cp = 0;
      int mp = 0;
      int ip = it;

      while (text.CharAt(it) != 0)
      {
        if (pattern.CharAt(ip) == '*')
        {
          if (pattern.CharAt(++ip) == 0)
            return true;
          mp = ip;
          cp = it + 1;
        }
        else if (pattern.CharAt(ip) == text.CharAt(it) || pattern.CharAt(ip) == '?')
        {
          ip++;
          it++;
        }
        else
        {
          ip = mp;
          it = cp++;
        }
      }

      while (pattern.CharAt(ip) == '*')
      {
        ip++;
      }
      return pattern.CharAt(ip) == 0;
    }
    public static char CharAt(this string s, int index)
    {
      if (index < s.Length)
        return s[index];
      return '\0';
    }
    public static bool IsNumber(this string val)
    {
      return Information.IsNumeric(val);
    }
    public static string IfNullOrEmpty(this string val, object defaultIfNull)
    {
      if(val.IsNull() || val.IsEmpty())
        return defaultIfNull.ToString();
      else
        return val;
    }
    public static string TrimEnd(this string str, string trimThis)
    {
      return str.TrimEnd(trimThis.ToCharArray());
    }
    public static string DefaultIfEmpty(this string str, string defaultString)
    {
      return str.IsEmpty() ? defaultString : str;
    }
  }
}